// 加入班级
import express from 'express';
import pool from "../importantApi/db_connection.js";

const router = express.Router();
router.post("/", async (req, res) => {
    const {userId, classId} = req.body;
    if (!userId || !classId) {
        return res.status(400).json({
            code: 400,
            error: "缺少必要参数"
        });
    }
    let [result] = await pool.query(`
            select count(*)    as count
            from user_class uc
            where uc.user_id = ${userId}
              and uc.class_id = ${classId}
        `)
    if (result[0].count > 0) {
        return res.status(201).json({
            code: 201,
            msg: "用户已在该班级中",
        })
    }
    let date = new Date()
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    let joinTime = `${year}-${String(month).padStart(2,'0')}-${String(day).padStart(2,'0')} ${String(hour).padStart(2,'0')}:${String(minute).padStart(2,'0')}`
    try {
        let [result] = await pool.query(`
            insert into user_class (class_id, user_id, jointime)
            values (${classId}, ${userId}, '${joinTime}')
        `)
        if (result.affectedRows > 0) {
            return res.status(200).json({
                code: 200,
                msg: "加入班级成功"
            })
        } else {
            return res.status(201).json({
                code: 201,
                msg: "加入班级失败"
            })
        }
    } catch (err) {
        console.log(err)
        return res.status(500).json({
            code: 500,
            error: err,
            msg: "加入班级错误：server error"
        })
    }
})
export default router;